<template>
  <PanerForm tag="div" :isShowBarDrawer="true" :caption="'编辑片段'">
    <template #body>
      <div class="d-row">
        <div class="d-form-group d-form-group-flex">
          <div class="d-form-label d-text-right">
            <label class="label-text">名称</label>
          </div>
          <div class="d-form-el">
            <input v-model="state.name" class="d-form-input" type="text" />
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-xs-12">
          <div class="d-form-label d-text-right">
            <label class="label-text">类型</label>
          </div>
          <div class="d-form-el">
            <select v-model="state.type" class="d-form-select">
              <option v-for="item in typeList" :key="item.id" :value="item.id">{{ item.text }}</option>
            </select>
          </div>
        </div>
        <div :class="state.type === 'singlepage' ? 'd-col-xs-12' : 'd-col-xs-6'" class="d-form-group d-form-group-flex">
          <div class="d-form-label d-text-right">
            <label class="label-text">编码</label>
          </div>
          <div class="d-form-el d-relative">
            <el-tabs v-if="isShowTab" v-model="activeView" class="coder-paner el-tabs-paner">
              <el-tab-pane v-if="state.type === 'html' || state.type === 'singlepage'" label="HTML" name="html">
                <Coder v-model="state.html" :height="'926px'" language="html" />
              </el-tab-pane>
              <el-tab-pane v-if="state.type === 'html' && state.type !== 'singlepage'" label="CSS/LESS" name="css" :lazy="true">
                <Coder v-model="state.css" :height="'926px'" language="css" />
              </el-tab-pane>
              <el-tab-pane v-if="state.type === 'html' && state.type !== 'singlepage'" label="JS" name="js" :lazy="true">
                <Coder v-model="state.js" :height="'926px'" language="javascript" />
              </el-tab-pane>
              <el-tab-pane v-if="state.type === 'vue'" label="Vue" name="vue" :lazy="true">
                <Coder v-model="state.vue" :height="'926px'" language="html" />
              </el-tab-pane>
            </el-tabs>
            <el-button v-if="state.type !== 'singlepage'" @click="handlePreview" class="btn-run" type="primary" plain size="small">运行</el-button>
          </div>
        </div>
        <div v-if="state.type !== 'singlepage'" class="d-form-group d-form-group-flex d-col-xs-6">
          <div class="d-form-label d-text-right">
            <label class="label-text">预览</label>
          </div>
          <div class="d-form-el">
            <div class="coder-preview">
              <component v-if="state.type === 'vue'" :is="viewComp"></component>
              <div v-else ref="previewView" class="preview-view"></div>
            </div>
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-xs-12">
          <div class="d-form-label d-text-right">
            <label class="label-text">描述</label>
          </div>
          <div class="d-form-el">
            <textarea v-model="state.description" class="d-form-textarea" rows="6"></textarea>
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-xs-6">
          <div class="d-form-label d-text-right">
            <label class="label-text">状态</label>
          </div>
          <div class="d-form-el">
            <select v-model="state.status" class="d-form-select">
              <option v-for="item in statusList" :key="item.id" :value="item.id">{{ item.text }}</option>
            </select>
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-xs-6">
          <div class="d-form-label d-text-right">
            <label class="label-text">排序</label>
          </div>
          <div class="d-form-el">
            <input v-model="state.order" class="d-form-input" type="text" placeholder="数值越大越靠前" />
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-xs-6">
          <div class="d-form-label d-text-right">
            <label class="label-text">标签</label>
          </div>
          <div class="d-form-el">
            <input v-model="state.labels" class="d-form-input" type="text" />
          </div>
        </div>
      </div>
    </template>
    <template #bar-drawer>
      <button @click="handleSubmit" class="d-btn d-btn-primary" type="button">提交</button>
      <button v-if="!isEdit" @click="handleReset" class="d-btn d-btn-default" type="reset">重置</button>
      <a v-d-goback class="d-btn d-btn-default">返回</a>
    </template>
  </PanerForm>
</template>

<script>
import Vue from 'vue'
import lesser from 'less'
import { PanerForm } from '@daelui/vdog/dist/pages.js'
import { Dialoger, FormCalendar, FormSelecter, Tabs, TabsItem } from '@daelui/vdog/dist/components.js'
import { Coder } from '@daelui/vdog/dist/coder.js'
import { zh as locale } from '@daelui/dogjs/dist/locale.js'
import { objecter, parser, domer } from '@daelui/dogjs/dist/components.js'
import coder, {resolveIdentify} from '@daelui/dogjs/dist/libs/coder.js'
import { STATUS } from '@daelui/dogjs/dist/constant.js'
import { state } from '../../../service/stock/index.js'
import snSer from '../../../service/action/snippet.action'

import * as Babel from '@babel/standalone'
const win = typeof self !== 'undefined' ? window : global
win.Babel = Babel

export default {
  components: {
    PanerForm,
    FormCalendar,
    Dialoger,
    FormSelecter,
    Coder,
    Tabs, TabsItem
  },

  data () {
    return {
      STATUS,
      isEdit: false, // 是否是编辑模式
      activeView: 'html',
      viewComp: 'div',
      isShowTab: true,
      // 表单数据
      state: {
        id: '',
        type: 'html',
        name: '',
        html: '',
        css: '',
        js: '',
        vue: window.atob('PHRlbXBsYXRlPgogIDxkaXY+PC9kaXY+CjwvdGVtcGxhdGU+Cgo8c2NyaXB0PgpleHBvcnQgZGVmYXVsdCB7CiAgZGF0YSAoKSB7CiAgICByZXR1cm4ge30KICB9LAoKICBtZXRob2RzOiB7CgogIH0KfQo8L3NjcmlwdD4KCjxzdHlsZSBsYW5nPSJsZXNzIj4KCjwvc3R5bGU+Cg=='),
        description: '',
        status: 1,
        order: 1,
        updateTime: '',
        updateUser: '',
        createTime: '',
        createUser: ''
      },
      // 类型列表
      typeList: state.snippetTypeList,
      // 状态列表
      statusList: state.statusList
    }
  },

  watch: {
    'state.type': function () {
      this.isShowTab = false
      if (this.state.type === 'vue') {
        this.activeView = 'vue'
      } else {
        this.activeView = 'html'
      }
      setTimeout(() => {
        this.isShowTab = true
      }, 200)
    }
  },

  methods: {
    /**
     * @function 加载数据
    */
    loadItem (id) {
      snSer.queryItem({ id }).then(result => {
        let data = result.data || {}
        this.state = data
        if (data.type === 'vue') {
          this.activeView = 'vue'
        }
        if (data.name) {
          document.title = data.name
        }
      })
    },

    /**
     * @function 提交
    */
    handleSubmit () {
      let defer = null
      let state = objecter.clone(this.state)
      delete this.state.createTime
      state.items = parser.stringify(state.items)
      state.cat = 1
      // 编辑
      if (this.isEdit) {
        defer = snSer.editItem(state)
      } else { // 添加
        defer = snSer.addItem(state)
      }
      defer.then(result => {
        if (result.success) {
          Dialoger.success(locale.action.success)
          // 添加则回到列表页
          if (!this.isEdit) {
            this.$router.push(this.getMicroRoute('/dview/snippet/list'))
          }
        } else {
          Dialoger.danger(locale.action.fail)
        }
      })
    },

    /**
     * @function 重置
    */
    handleReset () {

    },

    /**
     * @function 预览
    */
    handlePreview () {
      if (this.state.type === 'vue') {
        this.handlePreviewVue()
      } else {
        this.handlePreviewHtml()
      }
    },

    /**
     * @function 预览
    */
    handlePreviewHtml () {
      let html = resolveIdentify(this.state.html || '', $pig.identifyMap)
      let css = resolveIdentify(this.state.css || '', $pig.identifyMap)
      let js = resolveIdentify(this.state.js || '', $pig.identifyMap)
      this.$refs.previewView.innerHTML = `
        ${html}
      `
      this.outputCss = ''
      lesser.render(css).then((output) => {
        this.outputCss = output.css
      }).finally(() => {
        domer.appendElement('style', { type: 'text/css', innerHTML: this.outputCss || css}, this.$refs.previewView)
        // domer.appendElement('script', { type: 'text/javascript', innerHTML: coder.transformModuleUMD(js)}, this.$refs.previewView)
        coder.resolve(js, $pig)
      })
    },

    /**
     * @function 预览
    */
    handlePreviewVue () {
      coder.vue.resolve(this.state.vue, Vue, $pig).then(cp => {
        this.viewComp = cp
      })
    }
  },

  beforeMount () {
    let params = this.$route.params
    // 新建
    if (!params.id) {
      this.isEdit = false
    } else { // 编辑
      this.isEdit = true
      this.loadItem(params.id)
    }
  },

  mounted () {

  }
}
</script>

<style lang="less" scoped>
.d-form-label {
  width: 90px;
}
.coder-paner {
  /deep/.d-paner-item-content {
    height: 940px;
  }
}
.coder-preview {
  overflow: auto;
  padding: 8px;
  height: 980px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  .preview-view {
    height: 100%;
  }
}
.btn-run {
  position: absolute;
  right: 0;
  top: 0;
}
</style>
<style lang="less">
.d-form-product .d-editor-container {
  height: 842px;
  .quill-editor {
    height: 800px
  }
}
</style>
